using System;
using System.Collections;
using System.Collections.Generic;
using UMC.Data;
using UMC.Web;
using UMC.WorkFlow.Entities;
using UMC.WorkFlow.Form;

namespace UMC.WorkFlow
{

    /// <summary>
    /// 流程订阅
    /// </summary>
    [Apiumc("WorkFlow", "Subscribe", Auth = WebAuthType.User, Desc = "流程订阅")]
    class WorkFlowSubscribeActivity : WebActivity
    {
        string GetString(CommandType cmdType)
        {
            var sb = new System.Text.StringBuilder();
            if ((cmdType & CommandType.Submit) == CommandType.Submit)
            {
                sb.Append(",申请");
            }
            if ((cmdType & CommandType.Lock) == CommandType.Lock)
            {
                sb.Append(",挂起");
            }
            if ((cmdType & CommandType.Reject) == CommandType.Reject)
            {
                sb.Append(",驳回");
            }
            if ((cmdType & CommandType.Approval) == CommandType.Approval)
            {
                sb.Append(",通过");
            }
            if ((cmdType & CommandType.Apostille) == CommandType.Apostille)
            {
                sb.Append(",加签");
            }
            if ((cmdType & CommandType.Terminate) == CommandType.Terminate)
            {
                sb.Append(",终止");
            }
            if ((((int)cmdType) & 512) == 512)
            {
                sb.Append(",完结");
            }
            if (sb.Length > 1)
            {
                return sb.ToString(1, sb.Length - 1);
            }
            return "";
            //var form = new UIFormDialog() { Title = "SQL脚本" };
            //form.AddCheckBox("事件", "CommandType", "0")//.Put("保存", "1", (sett.CommandType & CommandType.Save) > 0)
            //.Put("提交", "2", (sett.CommandType & CommandType.Submit) > 0)
            //.Put("驳回", "4", (sett.CommandType & CommandType.Reject) > 0)
            //.Put("挂起", "8", (sett.CommandType & CommandType.Lock) > 0)
            //.Put("通过", "16", (sett.CommandType & CommandType.Approval) > 0)
            //.Put("加签", "64", (sett.CommandType & CommandType.Apostille) > 0)
            //.Put("终止", "32", (sett.CommandType & CommandType.Terminate) > 0)
            //.Put("完结", "512", (((int)sett.CommandType) & 512) > 0);
        }

        public override void ProcessActivity(WebRequest request, WebResponse response)
        {
            TaskForm taskForm = null;
            var Task = UMC.Data.Utility.UInt64Parse(this.AsyncDialog("Task", k =>
            {
                var Code = this.AsyncDialog("Code", "none");
                if (Code == "none")
                {
                    this.Prompt("缺少参数");
                }
                taskForm = DataFactory.Instance().TaskForm(Code);

                // TaskRuntime.Database.ObjectEntity<TaskForm>().Where.And().Equal(new TaskForm
                // {
                //     Code = Code
                // }).Entities.Single();
                if (taskForm == null)
                {
                    this.Prompt("未有此流程");
                }
                return this.DialogValue(taskForm.TaskId.ToString());

            })).Value;
            if (taskForm == null)
            {
                // var design = UMC.WorkFlow.TaskRuntime.Database.ObjectEntity<TaskDesign>()
                //     .Where.Or(new TaskDesign { Id = Task, TaskId = Task }).Entities.Single();
                taskForm =
                 DataFactory.Instance().TaskForm(Task);

                if (taskForm == null)
                {
                    this.Prompt("未有此流程");
                }
            }
            var ShapeId = this.AsyncDialog("ShapeId", gg =>
            {
                var form = request.SendValues ?? new UMC.Web.WebMeta();
                if (form.ContainsKey("limit") == false)
                {
                    this.Context.Send(new UISectionBuilder(request.Model, request.Command, new WebMeta(request.Arguments.GetDictionary()))
                        .RefreshEvent("WorkFlow.Subscribe")
                            .Builder(), true);
                }
                var ui = UMC.Web.UISection.Create(new UITitle("流程订阅"));

                ui.Title.Right(new UIEventText("新增")
                    .Click(new UIClick(request.Model, request.Command, new WebMeta(request.Arguments).Put(gg, "NEWS"))));
                var staffs = new List<TaskSubscribe>(DataFactory.Instance().TaskSubscribe(taskForm.TaskId.Value));




                foreach (var u in staffs)
                {
                    var ui3 = ui.NewSection().AddCell("订阅人员", String.Format("{0}({1})", u.Alias, u.Username))
                    .AddCell("订阅节点", String.Format("{0}({1})", u.ShapeName, u.ShapeId));


                    var cell = UICell.Create("Cell", new WebMeta().Put("value", GetString(u.SubscribeEvent ?? CommandType.Undefine)).Put("text", "订阅事件"));

                    ui3.Delete(cell, new UIEventText().Click(new Web.UIClick(request.Model, request.Command, new WebMeta(request.Arguments).Put(gg, u.ShapeId).Put("Name", u.Username))));
                }
                if (staffs.Count == 0)
                {
                    ui.Add("Desc", new UMC.Web.WebMeta().Put("desc", "流程未设置订阅人员").Put("icon", "\uEA05")
                        , new UMC.Web.WebMeta().Put("desc", "{icon}\n{desc}"),
                 new UIStyle().Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60)));//.Name 

                }


                response.Redirect(ui);
                return this.DialogValue("none");
            });
            if (String.Equals(ShapeId, "NEWS"))
            {
                var v = this.AsyncDialog("CommandType", g =>
                {
                    var form = new UIFormDialog() { Title = "订阅事情" };
                    form.AddCheckBox("事件", "SubscribeEvent", "0")//.Put("保存", "1", (sett.CommandType & CommandType.Save) > 0)
                    .Put("申请", "2")
                    .Put("驳回", "4")
                    .Put("挂起", "8")
                    .Put("通过", "16")
                    .Put("加签", "64")
                    .Put("终止", "32")
                    .Put("完结", "512");
                    form.AddOption("订阅节点", "ShareId")
                      .Command(request.Model, "Shape", new WebMeta().Put("Task", Task).Put("Key", "ShareId"));
                    form.AddOption("订阅人员", "Username").Command("Settings", "SelectUser");

                    form.Submit("确认", "WorkFlow.Subscribe");
                    return form;
                });
                var sett = new TaskSubscribe();
                sett.SubscribeEvent = CommandType.Undefine;
                var vs = v["SubscribeEvent"].Split(',');
                foreach (var c in vs)
                {

                    sett.SubscribeEvent = sett.SubscribeEvent | (CommandType)UMC.Data.Utility.EnumParse(c, CommandType.Undefine);
                }
                sett.ShapeId = v["ShareId"];
                sett.ShapeName = v["ShareId_Text"];
                sett.Username = v["Username"];
                sett.Alias = v["Username_Text"];
                sett.TaskId = taskForm.TaskId;
                DataFactory.Instance().Put(new TaskSubscribe
                {
                    TaskId = taskForm.TaskId,
                    ShapeId = sett.ShapeId,
                    Username = sett.Username

                });

            }
            else
            {
                var name = this.AsyncDialog("Name", "none");

                DataFactory.Instance().Delete(new TaskSubscribe
                {
                    TaskId = taskForm.TaskId,
                    ShapeId = ShapeId,
                    Username = name

                });//.Entities.Delete();
            }
            this.Context.Send("WorkFlow.Subscribe", true);


        }
    }
}